<script setup lang="ts">
import { ref, type PropType } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import path from 'path-browserify'

const props = defineProps({
  item: {
    type: Object as PropType<RouteRecordRaw>,
  },
  basePath: {
    type: String,
    default: '',
  },
})

const onlyOneChild = ref<RouteRecordRaw>()

// 获取需要展示的唯一一个子路由
function showOnlyOneChild(children: RouteRecordRaw[] = []) {
  const showingChildren = children.filter((item) => {
    if (item.meta?.hidden) {
      return false
    } else {
      onlyOneChild.value = item
      return true
    }
  })

  if (showingChildren.length === 1) {
    return true
  }
}

function resolvePath(routePath: string) {
  const httpReg = /^http(s?):\/\//
  if (httpReg.test(routePath) || httpReg.test(props.basePath)) {
    return routePath || props.basePath
  } else {
    // 使用path.posix.resolve替代path.resolve 避免windows环境下使用electron出现盘符问题
    return path.posix.resolve(props.basePath, routePath)
  }
}
</script>

<template>
  <template v-if="!item?.meta?.hidden">
    <el-menu-item v-if="showOnlyOneChild(item?.children)" :index="resolvePath(onlyOneChild!.path)">
      <Document
        style="width: 18px; color: rgb(144, 147, 153); padding-right: 6px"
        v-if="onlyOneChild?.meta?.title == '内容管理'"
      />
      <HomeFilled
        style="width: 18px; color: rgb(144, 147, 153); padding-right: 6px"
        v-if="onlyOneChild?.meta?.title == '数据概览'"
      />
      <Promotion
        style="width: 18px; color: rgb(144, 147, 153); padding-right: 6px"
        v-if="onlyOneChild?.meta?.title == '发布文章'"
      />
      <span>{{ onlyOneChild?.meta?.title }}</span>
    </el-menu-item>
  </template>
</template>

<style lang="scss" scoped></style>
